<template>
  <div id="product-detail">
    <Navbar />
    <LoginDialog v-if="showLoginDialog" @close="showLoginDialog = false" @loginSuccess="handleLoginSuccess" />
    <RegisterDialog v-if="showRegisterDialog" @close="showRegisterDialog = false" />

    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <p>{{ errorMessage }}</p>
      <p v-if="errorStatus === '404'">商品不存在或已下架</p>
      <button @click="reloadProduct">重新加载</button>
    </div>

    <div v-else class="product-detail-container">
      <div class="product-detail-main">
        <div class="product-image-section">
          <img :src="product.image_url || '/default-image.png'" alt="product" class="product-detail-image"
            @error="handleImageError" />
        </div>
        <div class="product-detail-right">
          <h2>{{ product.name || '商品名称' }}</h2>
          <span class="product-price">¥{{ product.price.toFixed(2) }}</span>
          <p class="product-description">库存：{{ product.stock_quantity || '未知' }} 件</p>

          <div class="quantity-group">
            <span>购买数量：</span>
            <input type="number" v-model.number="buyQuantity" :min="1" :max="product.stock_quantity"
              class="quantity-input" />
          </div>

          <div class="button-group">
            <button class="customer-service-button">客服</button>
            <button class="store-button">店铺</button>
            <button class="collect-button" @click="toggleCollect">
              <i :class="isCollected ? 'fa-solid fa-star text-yellow-400' : 'fa-regular fa-star'"></i>
              {{ isCollected ? '已收藏' : '收藏' }}
            </button>
            <button class="add-to-cart-button" @click="addToCart">加入购物车</button>
            <button class="buy-now-button" @click="buyNow">立即购买</button>
          </div>
        </div>
      </div>

      <nav class="bottom-navbar" :class="{ fixed: isBottomSticky }">
        <div class="additional-nav">
          <a href="#product-review-section" class="nav-item" @click="activeTab = 'userReview'"
            :class="{ active: activeTab === 'userReview' }">
            用户评价
          </a>
          <a href="#product-parameter-section" class="nav-item" @click="activeTab = 'parameterInfo'"
            :class="{ active: activeTab === 'parameterInfo' }">
            参数信息
          </a>
          <a href="#product-image-text-section" class="nav-item" @click="activeTab = 'imageTextDetail'"
            :class="{ active: activeTab === 'imageTextDetail' }">
            图文详情
          </a>
        </div>
      </nav>

      <div class="product-detail-additional">
        <div class="product-review-section" id="product-review-section">
          <h3>商品评价</h3>
          <ul>
            <li v-if="!product.reviews || product.reviews.length === 0">
              <p class="review-author">暂无评价</p>
              <p class="review-content">暂无评价内容</p>
            </li>
            <li v-for="(review, index) in product.reviews" :key="index">
              <p class="review-author">{{ review.author || '匿名用户' }}</p>
              <p class="review-content">{{ review.content || '该用户未填写评价' }}</p>
            </li>
          </ul>
        </div>

        <div class="product-parameter-section" id="product-parameter-section">
          <h3>参数详情</h3>
          <table>
            <tr v-for="(param, index) in product.parameters || []" :key="index">
              <td>{{ param.name }}</td>
              <td>{{ param.value }}</td>
            </tr>
          </table>
        </div>

        <div class="product-image-text-section" id="product-image-text-section">
          <h3>图文详情</h3>
          <img :src="product.image_url || '/default-image.png'" alt="product" class="product-detail-image"
            @error="handleImageError" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import LoginDialog from "../../components/LoginDialog.vue";
import Navbar from "../../components/Navbar.vue";
import axios from 'axios';
import { useUserStore } from '@/stores/userStore';

const route = useRoute();
const router = useRouter();
const productId = ref(route.params.id);
const product = ref({});
const order = ref({});
const loading = ref(true);
const error = ref(false);
const errorMessage = ref("");
const errorStatus = ref("");
const userStore = useUserStore();

const isLoggedIn = ref(localStorage.getItem("isLoggedIn") === "true");
const showLoginDialog = ref(false);
const showRegisterDialog = ref(false);
const isCollected = ref(false);
const buyQuantity = ref(1);
const activeTab = ref("userReview");

const currentUser = ref(localStorage.getItem("currentUser") || null);

const getCurrentUser = () => localStorage.getItem("currentUser");
const getCartKey = () => `cart_${getCurrentUser()}`;
const getFavoritesKey = () => `favorites_${getCurrentUser()}`;

// 检查商品是否已被收藏（从后端获取数据）
const checkFavoriteStatus = async (productId) => {
  if (!isLoggedIn.value) return false;
  try {
    const response = await axios.get(
      `http://localhost:3000/favorites?userId=${getCurrentUser()}&productId=${productId}`
    );
    return response.data.length > 0;
  } catch (error) {
    console.error("检查收藏状态失败:", error);
    return false;
  }
};

// 加载商品数据和收藏状态
const loadProductData = async () => {
  loading.value = true;
  error.value = false;
  try {
    console.log("请求商品ID:", productId.value, "类型:", typeof productId.value);
    const response = await fetch(`http://localhost:3000/products/${productId.value}`);
    if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);

    const targetProduct = await response.json();
    if (!targetProduct) throw new Error("商品不存在");

    product.value = {
      ...targetProduct,
      price: parseFloat(targetProduct.price),
      stock_quantity: parseInt(targetProduct.stock_quantity),
      shopName: targetProduct.shopName,
      type: targetProduct.type || "default",
      reviews: targetProduct.reviews || [],
      parameters: targetProduct.parameters || [],
    };

    console.log("加载商品详情成功:", product.value);
    
    // 从后端获取收藏状态
    isCollected.value = await checkFavoriteStatus(targetProduct.id);
  } catch (err) {
    console.error("加载失败:", err);
    error.value = true;
    errorMessage.value = err.message || "商品加载失败，请重试";
    errorStatus.value = err.message.includes("HTTP") ? err.message.split(" ")[2] : "500";
  } finally {
    loading.value = false;
  }
};

const reloadProduct = () => loadProductData();

watch(() => route.params.id, (newId) => {
  productId.value = newId;
  loadProductData();
}, { immediate: true });

const handleImageError = (e) => {
  e.target.src = "/default-image.png";
};

// 加入购物车
const addToCart = async () => {
  if (!isLoggedIn.value) {
    showLoginDialog.value = true;
    return;
  }

  try {
    //获取或创建用户购物车
    let userCart = (await axios.get(`http://localhost:3000/carts?userId=${getCurrentUser()}`)).data[0];
    if (!userCart) {
      userCart = await axios.post("http://localhost:3000/carts", { 
        userId: getCurrentUser(), 
        items: [] 
      });
      userCart = userCart.data;
    }

    //检查商品是否已存在于购物车
    const itemIndex = userCart.items.findIndex(item => item.productId === product.value.id);
    const newQuantity = itemIndex !== -1 
      ? userCart.items[itemIndex].quantity + buyQuantity.value 
      : buyQuantity.value;

    // 3. 校验库存
    if (newQuantity > product.value.stock_quantity) {
      throw new Error(`库存不足，最多可购买 ${product.value.stock_quantity} 件`);
    }

    // 4. 更新购物车商品
    if (itemIndex !== -1) {
      userCart.items[itemIndex].quantity = newQuantity;
    } else {
      userCart.items.push({
        productId: product.value.id,
        name: product.value.name,
        price: product.value.price,
        quantity: buyQuantity.value,
        image_url: product.value.image_url,
        shopName: product.value.shopName,
        isChecked: false, // 默认不选中
      });
    }

    // 5. 保存到服务器
    await axios.patch(`http://localhost:3000/carts/${userCart.id}`, { items: userCart.items });
    
    ElMessage.success(`已成功添加 ${buyQuantity.value} 件商品到购物车！`);
    buyQuantity.value = 1; // 重置数量
  } catch (error) {
    console.error('添加到购物车失败:', error);
    ElMessage.error(error.message || '添加到购物车失败，请重试');
  }
};

// 立即购买
// 立即购买
const buyNow = async () => {
  if (!isLoggedIn.value) {
    showLoginDialog.value = true;
    return;
  }

  try {
    let sellerInfo = {};
    try {
      sellerInfo = JSON.parse(product.value.userId || "{}");
    } catch (err) {
      console.error("解析卖家信息失败:", err);
    }

    const currentUserId = userStore.user?.id;
    if (!currentUserId) {
      throw new Error('未获取到用户ID，请重新登录');
    }
    const orderData = {
      userId: getCurrentUser(),
      // 从解析后的卖家信息中获取id作为merchantid
      merchantid: sellerInfo.id || "",
      products: [{
        productId: product.value.id,
        name: product.value.name,
        price: product.value.price,
        quantity: buyQuantity.value,
        image_url: product.value.image_url,
        shopName: product.value.shopName,
      }],
      totalPrice: product.value.price * buyQuantity.value,
      status: "待接单",
      createdAt: new Date().toISOString(),
    };

    const response = await axios.post('http://localhost:3000/orders', orderData);
    console.log('订单创建成功:', response.data);


     // 发送通知给卖家
        const notificationData = {
            sellerId: product.value.userId.id,
            userId: currentUserId, // 当前用户ID
            orderId: response.data.id,
            content: "我已下单，待发货",
            timestamp: new Date().toISOString(),
            read: false
            
        };
    await axios.post('http://localhost:3000/sellermessages', notificationData);

    
    ElMessage.success(`已成功购买 ${buyQuantity.value} 件商品！`);
    router.push('/main/profile/user-center/orders');
    buyQuantity.value = 1;
  } catch (error) {
    console.error('创建订单失败:', error);
    ElMessage.error('订单创建失败，请重试');
  }

// 新增：更新商品库存的函数
const updateProductStock = async (productId, quantityToDeduct) => {
  try {
    // 获取当前商品库存
    const productResponse = await axios.get(`http://localhost:3000/products/${productId}`);
    const currentStock = productResponse.data.stock_quantity;
    
    // 计算新库存（确保库存不为负）
    const newStock = Math.max(0, currentStock - quantityToDeduct);
    
    // 更新库存
    await axios.patch(`http://localhost:3000/products/${productId}`, {
      stock_quantity: newStock
    });
    
    console.log(`商品 ${productId} 库存已更新，当前库存: ${newStock}`);
    
    // 如果是本地开发，更新前端缓存的商品数据（可选）
    if (product.value) {
      product.value.stock_quantity = newStock;
    }
  } catch (error) {
    console.error('更新库存失败:', error);
    ElMessage.warning('库存更新失败，但订单已创建');
  }
};
};

// 收藏/取消收藏功能（核心修改点）
const toggleCollect = async () => {
  if (!currentUser.value) {
    showLoginDialog.value = true;
    return;
  }

  const userId = currentUser.value;
  const productId = product.value.id;
  const productData = { ...product.value }; // 完整商品信息

  try {
    const existingFavorites = await axios.get(
      `http://localhost:3000/favorites?userId=${userId}&productId=${productId}`
    );

    if (existingFavorites.data.length > 0) {
      // 已收藏：删除收藏记录
      const favoriteId = existingFavorites.data[0].id;
      await axios.delete(`http://localhost:3000/favorites/${favoriteId}`);
      ElMessage.success("已取消收藏");
    } else {
      // 未收藏：添加收藏记录
      const newFavorite = {
        userId,
        productId,
        product: productData, // 存储完整商品信息
        createdAt: new Date().toISOString()
      };
      await axios.post("http://localhost:3000/favorites", newFavorite);
      ElMessage.success("收藏成功！");
    }

    isCollected.value = !isCollected.value;
    updateLocalFavoritesCache();
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

// 更新本地收藏缓存（可选优化）
const updateLocalFavoritesCache = async () => {
  if (!isLoggedIn.value) return;
  
  try {
    const favorites = await axios.get(
      `http://localhost:3000/favorites?userId=${getCurrentUser()}`
    );
    localStorage.setItem(getFavoritesKey(), JSON.stringify(favorites.data));
  } catch (error) {
    console.error("更新本地收藏缓存失败:", error);
  }
};

const handleLoginSuccess = () => {
  isLoggedIn.value = true;
  currentUser.value = localStorage.getItem("currentUser");
  localStorage.setItem("isLoggedIn", "true");
  showLoginDialog.value = false;
  loadProductData(); // 重新加载商品数据和收藏状态
};

const isBottomSticky = ref(false);
const handleBottomScroll = () => {
  isBottomSticky.value = window.pageYOffset > 0;
};

onMounted(() => {
  loadProductData();
  window.addEventListener("scroll", handleBottomScroll);
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleBottomScroll);
});
</script>

<style scoped>
.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #E05649;
  padding: 10px 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.top-navbar.fixed {
  /* background-color: #fff; */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  color: #333;
}

.top-navbar.fixed .nav-link,
.top-navbar.fixed .sign-in-button,
.top-navbar.fixed .register-button,
.top-navbar.fixed .sign-out-button {
  color: #333;
}

.nav-link {
  margin-right: 20px;
  text-decoration: none;
  color: #fff;
  font-weight: 500;
}

.nav-link:hover {
  color: #230303;
}

.sign-in-button,
.register-button,
.sign-out-button {
  background-color: transparent;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  color: #fff;
  transition: all 0.3s ease;
}

.sign-in-button:hover,
.register-button:hover,
.sign-out-button:hover {
  opacity: 0.8;
}

/* 商品详情容器 */
.product-detail-container {
  padding: 20px;
  text-align: center;
  margin-top: 60px;
  /* 导航栏高度 */
  background-color: #f3f3f3;
}

.product-detail-main {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px 10%;
  margin-bottom: 20px;
}

.product-image-section {
  margin: 20px 0;
}

.product-detail-image {
  width: 250px;
  height: auto;
  border: 1px solid #eee;
  padding: 5px;
  border-radius: 10px;
  box-shadow: #666 3px 3px 3px;
}

.product-info-section h2 {
  font-size: 1.3em;
  margin-bottom: 10px;
  color: #333;
}

.product-price {
  font-size: 1.2em;
  color: #e05649;
  font-weight: bold;
  margin-bottom: 15px;
}

.product-description {
  font-size: 0.95em;
  color: #666;
  line-height: 1.5;
  margin-bottom: 20px;
}

/* 购买数量选择器 */
.quantity-group {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 15px 0;
  color: #333;
}

.quantity-input {
  width: 60px;
  padding: 6px;
  margin-left: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
}

.button-group {
  margin: 20px 0;
}

.button-group button {
  margin: 0 5px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.customer-service-button,
.store-button {
  background-color: #f0f0f0;
}

.collect-button {
  color: #e05649;
  border: 1px solid #e05649;
  background-color: transparent;
}

.add-to-cart-button,
.buy-now-button {
  background-color: #e05649;
  color: white;
}

/* 商品评价 */
.product-review-section {
  margin-top: 30px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
  text-align: left;
  max-width: 600px;
  margin: 0 auto;
  background: #f0f0f0;
}

.review-author {
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.review-content {
  color: #666;
  line-height: 1.4;
}

/* 参数详情 */
.product-parameter-section {
  margin-top: 30px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
  text-align: left;
  max-width: 600px;
  margin: 0 auto;
}

/* 图文详情 */
.product-text-image-section {

  margin-top: 30px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
  text-align: left;
  max-width: 600px;
  margin: 0 auto;
}

.product-text-image-section img {
  width: 100%;
  height: auto;
}

/* 店铺信息 */
.store-info-section {
  margin-top: 30px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
  text-align: left;
  max-width: 600px;
  margin: 0 auto;
}

/* 加载/错误状态 */
.loading-container,
.error-container {
  padding: 200px 0;
  text-align: center;
  background-color: #f3f3f3;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #e05649;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin: 0 auto 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-container button {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #e05649;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.additional-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  overflow: hidden;
  padding: 10px 20px;
  position: relative;
  /* bottom: 0; */
  left: 0;
  right: 0;
  z-index: 30;
  width: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.additional-nav a {
  color: #333;
}

.additional-nav a:hover {
  color: #e05649;
}

.additional-nav a:active,
.additional-nav a:focus {
  color: #e05649;
}

.product-detail-additional {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.product-detail-additional h2 {
  font-size: 1.5em;
  margin-bottom: 10px;
  color: #333;
}

.product-detail-additional p {
  font-size: 1em;
  color: #666;
  line-height: 1.5;
  margin-bottom: 20px;
}

.product-detail-additional img {
  width: 100%;
  height: auto;
}

.product-detail-additional .product-detail-image {
  width: 250px;
  height: auto;
  border: 1px solid #eee;
  padding: 5px;
  border-radius: 10px;
}

.product-detail-additional .product-price {
  font-size: 1.2em;
  color: #e05649;
}

.product-detail-additional .product-description {
  font-size: 0.95em;
  color: #666;
  line-height: 1.5;
}
.product-detail-right{
  align-self: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 10px;
}
</style>